package com.koron.css2.newProjectCenter.impl;

import com.koron.css2.baseConfig.mapper.BusinessAreaMapper;
import com.koron.css2.clientCenter.bean.CtmInfoBean;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.common.dto.AttachmentDto;
import com.koron.css2.common.service.AbstractExportExcel;
import com.koron.css2.newProjectCenter.bean.query.PjInfoQueryBean;
import com.koron.css2.newProjectCenter.mapper.PjCollectionMapper;
import com.koron.css2.newProjectCenter.mapper.PjInfoMapper;
import com.koron.css2.newProjectCenter.vo.PjInfoListVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.DateUtils;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class PjInfoListExport extends AbstractExportExcel {

    @Override
    public AttachmentDto getAttachment(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        PjInfoQueryBean pjInfoQueryBean = JsonUtils.objectToPojo(req.getData(), PjInfoQueryBean.class);
        PjInfoMapper pjInfoMapper = factory.getMapper(PjInfoMapper.class);
        Map<String, String> PIS = Tools.mapDicByCode(factory, "PIS");
        Map<String, String> PPT = Tools.mapDicByCode(factory, "PPT");
        BusinessAreaMapper businessAreaMapper = factory.getMapper(BusinessAreaMapper.class);
        PjCollectionMapper pjCollectionMapper = factory.getMapper(PjCollectionMapper.class);
        // 1. 优化查询，非必要，不联表
        List<String> fuzzyItems = pjInfoQueryBean.getFuzzyItems();
        int userCtmTempFlag = 0;
        if (fuzzyItems != null && (fuzzyItems.contains("b.ctm_name") || fuzzyItems.contains("b.cert_no") || fuzzyItems.contains("b.mobile"))) {
            userCtmTempFlag = 1;
            pjInfoQueryBean.setUserCtmTempFlag(userCtmTempFlag);
        }
        // 2. 查询列表
        List<PjInfoListVO> list = pjInfoMapper.selectList(pjInfoQueryBean);
        // 3. 查询对应的客户信息并转map
        Map<String, CtmInfoBean> ctmMap = null;
        if (list != null && list.size() > 0 && userCtmTempFlag == 0) {
            List<String> userCtmTempIdList = list.stream().map(PjInfoListVO::getUserCtmTempId).collect(Collectors.toList());
            CtmInfoMapper ctmInfoMapper = factory.getMapper(CtmInfoMapper.class);
            List<CtmInfoBean> ctmInfoBeanList = ctmInfoMapper.getListByIdList(userCtmTempIdList, CtmInfoBean.CTMTEMP);
            ctmMap = ctmInfoBeanList.stream().collect(Collectors.toMap(CtmInfoBean::getId, Function.identity()));
        }
        for (PjInfoListVO bean : list) {
            if(bean.getPrepayType()!=null&& "1".equals(bean.getPrepayType())){
                bean.setPrepayType("预代决");
            }
            if(bean.getPrepayType()!=null&& "2".equals(bean.getPrepayType())){
                bean.setPrepayType("预决算");
            }
            if(bean.getBearCost()!=null&& "1".equals(bean.getBearCost())){
                bean.setBearCost("工程费");
            }
            if(bean.getBearCost()!=null&& "2".equals(bean.getBearCost())){
                bean.setBearCost("设计费");
            }
            if(bean.getNoBearCost()!=null&& "1".equals(bean.getNoBearCost())){
                bean.setNoBearCost("工程费（水表费）");
            }
            if(bean.getNoBearCost()!=null&& "2".equals(bean.getNoBearCost())){
                bean.setNoBearCost("设计费");
            }
            // 4.1 已用时间=工程完工时间（没完工的使用当前时间）-报装时间
            String completionDate = bean.getCompletionDate();
            Integer usedTime = null;
            if (StringUtils.isNotEmpty(completionDate)) {
                Date date = null;
                try {
                    date = new SimpleDateFormat("yyyy-MM-dd").parse(completionDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                usedTime = DateUtils.betweenDays(date, bean.getBillDate());
            } else {
                usedTime = DateUtils.betweenDays(new Date(), bean.getBillDate());
            }
            bean.setUsedTime(usedTime + "天");
            // 4.2 转换数据字典
            bean.setSourceFlag(PIS.get(bean.getSourceFlag()));
            bean.setPjType(PPT.get(bean.getPjType()));
            // 4.3 转换状态
            bean.setProcessState(Tools.transProcessStatus(bean.getProcessState()));
            //超期状态 政务平台同步为null
            if (null!=bean.getTimeOutFlag()&&bean.getTimeOutFlag() == 1) {
                bean.setTimeOutFlagName("已超期");
            } else {
                bean.setTimeOutFlagName("未超期");
            }
            // 4.5 ctmName,certNo,mobile
            if (userCtmTempFlag == 0 && ctmMap != null && ctmMap.size() > 0&&ctmMap.containsKey(bean.getUserCtmTempId())) {
                bean.setCtmName(ctmMap.get(bean.getUserCtmTempId()).getCtmName());
                bean.setCertNo(ctmMap.get(bean.getUserCtmTempId()).getCertNo());
                bean.setMobile(ctmMap.get(bean.getUserCtmTempId()).getMobile());
            }

            if (bean.getDelayState() == 1) {
                bean.setDelayStateName("已延期");
            } else {
                bean.setDelayStateName("未延期");
            }

            // 已废弃 -> 已终止
            String processState = bean.getProcessState();
            if (StringUtils.isNotEmpty(processState) && processState.equals("已废弃")) {
                bean.setProcessState("已终止");
            }
            String processName = bean.getProcessName();
            if (StringUtils.isNotEmpty(processName) && processName.equals("已废弃")) {
                bean.setProcessName("已终止");
            }

            // 4.7 已缴费标志
            Integer payOffFlag = bean.getPayOffFlag();
            if (payOffFlag != null && payOffFlag == 0) {
                bean.setPayOffFlagName("未缴清");
            }
            if (payOffFlag != null && payOffFlag == 1) {
                bean.setPayOffFlagName("已缴清");
            }
            // 4.8 已签合同标志
            Integer signContractFlag = bean.getSignContractFlag();
            if (signContractFlag != null && signContractFlag == 0) {
                bean.setSignContractFlagName("未签");
            }
            if (signContractFlag != null && signContractFlag == 1) {
                bean.setSignContractFlagName("已签");
            }
            // 4.9 包装日期
            String billDateString = Tools.formatDateToString(bean.getBillDate());
            bean.setBillDateString(billDateString);
            //营业区域转换
            if (StringUtils.isNotBlank(bean.getBusinessArea())){
                bean.setBusinessArea(
                        businessAreaMapper.findBusinessAreaById(bean.getBusinessArea(), userInfo.getCurWaterCode()));
            }
            // 通过工程单据ID查询出工程收款日期
            Date paymentDate = pjCollectionMapper.getPaymentDateByPjId(bean.getId());
            if (paymentDate != null){
                bean.setChargeDate(DateUtils.parseDate(paymentDate, "yyyy-MM-dd"));
            }
        }
        // 5. 导出excel
        AttachmentDto attachment = new AttachmentDto();
        attachment.setBtlTemplate("PjInfoListExport.btl");
        attachment.setData(list);
        attachment.setFilename("工程报装列表导出");
        attachment.setFileTemplate("PjInfoListExport.xlsx");
        attachment.setFileType("excel");
        return attachment;
    }
}
